import * as React from 'react';
import {Component} from 'react';
import { 
  MessageBar,
  MessageBarType,
  Stack, 
  IStackStyles,
  IIconProps, 
  IStackTokens,
  IStackItemStyles, 
  ICommandBarStyles,
  IButtonStyles, 
  IStyleSet,
  Checkbox,
  Label,
  Link,
  ILinkStyles,
  ILabelStyles, 
  Pivot, 
  IPivotStyles,
  PivotItem, 
  mergeStyleSets,
  IContextualMenuItem
} from '@fluentui/react'; 
import {
  ContextualMenuItemType,
  IContextualMenuProps,
  IContextualMenuItemProps,
} from '@fluentui/react/lib/ContextualMenu';
import { TeachingBubble } from '@fluentui/react/lib/TeachingBubble';
import { CommandBar, ICommandBarItemProps, } from '@fluentui/react/lib/CommandBar';
import { DefaultButton, PrimaryButton, IButtonProps } from '@fluentui/react/lib/Button';
import { Panel,PanelType } from '@fluentui/react/lib/Panel';
import { DetailsList, DetailsListLayoutMode,SelectionMode,Selection } from '@fluentui/react/lib/DetailsList';
import { ScrollablePane } from '@fluentui/react/lib/ScrollablePane';
import { Dialog, DialogFooter } from '@fluentui/react/lib/Dialog'; 
import { Callout } from '@fluentui/react/lib/Callout';
import './BodyProvit.css';
import {ProvitTeam} from './ProvitTeam.tsx';
import JobTrigger from './JobTrigger.tsx';
import JobEditor from './JobEditor.tsx';
import http from './RequestUtl.ts';
import { transform } from 'typescript';

const pivotStyles:Partial<IPivotStyles>={
    root: {
        width:90,
        // backgroundColor:'#ebebeb',
        backgroundImage:'linear-gradient(to right,#ebebeb, #ebebeb 90%, #dfdfdf)'
    },
    link:{
        display:'block',
        width:90,
        padding:'5px 0px',
        height:'auto',
        fontSize:12,
        color:'#616161',
    },
    linkIsSelected:{
        color:'#0078d4',
    },
    icon:{
        display:'block',
        height: 20,
        fontSize: 25,
    }
}
const pivotitemClass='pivotitems_ver';
const labelStyles: Partial<IStyleSet<ILabelStyles>> = {
  root: { marginTop: 10 },
};
const linkStyles:Partial<IStyleSet<ILinkStyles>>={
  root: {
    //  marginTop: 10,
     fontSize:14,
     fontWeight:600,
     color:'#036ab9', 
     backgroundColor:'#e3e3e3',
     padding:'0px 15px 0px 15px',
  }, 
}
 
const rl_stack_styles:IStackStyles = {
    root: {
      background:'transparent',
      overflow: 'hidden',
      width:'100%',
      borderBottom:'solid 1px #ebebeb',
    },
};
const rl_stack_v_styles:IStackStyles = {
    root: {
      background:'rgb(245, 245, 245)',
      overflow: 'hidden',
      width:'100%',
      height:'100%', 
      padding:'0px 10px',
    },
};
const settingButtonStyles:Partial<IButtonStyles>={
    root:{
        borderRadius:'5px',
        borderColor:'#d1d1d1',
    }
}
const opButtonStyles:Partial<IButtonStyles>={
  root:{
    width:40,
    minWidth:40,
    borderWidth:0,
    height:22,
    lineHeight:22,
    backgroundColor:'transparent',
  },
  rootHovered:{
    backgroundColor:'transparent',
  },
  rootFocused:{
    backgroundColor:'transparent',
  }
}

const rl_stackitem_styles: IStackItemStyles = {
    root: {
      alignItems: 'center', 
      display: 'flex',
      width:300,
      flex:'none',
      height:60,
      justifyContent: 'center',
      overflow: 'hidden',
    },
  };
const datalist_stack_styles:IStackItemStyles = {
  root: {
    flex:'1',
    height:'100%',
  },
};
const rl_stackitem_msgbar_styles: IStackItemStyles = {
  root: {
    alignItems: 'center', 
    display: 'flex',
    flex:'1', 
    height:60,
    justifyContent: 'center',
    overflow: 'hidden',
  },
};
const rl_stackitem_vedio_styles: IStackItemStyles = {
    root: {
      alignItems: 'center', 
      display: 'flex',
      flex:'none',
      width:150,
      height:60,
      justifyContent: 'center',
      overflow: 'hidden',
    },
  };

const innerStackTokens: IStackTokens = {
  childrenGap: 0,//子元素之间的间隙
  padding: 0,//padding
};

const commandButtonStyls:Partial<ICommandBarStyles>={
  root:{
      padding:'0px',
      background:'transparent',
      borderBottom:'solid 1px #e0e0e0',
  },
}

const DataListClass=mergeStyleSets({
  wrapper:{
    width:'100%',
    height:'100%',
    position:'relative',
    maxHeight:'inherit',
  },
})

const pivot2Styles:Partial<IPivotStyles>={
  root: {
      backgroundColor:'#f5f5f5',
 },
  link:{  
      padding:'5px',
      height:60,
      fontSize:14,
      color:'#616161',
  },
}
const jobModelProps = {
  isBlocking: true,
  topOffsetFixed: true,
  innerWidth:700,
};

const overflowProps: IButtonProps = { ariaLabel: 'More commands' };
const rl_menu_items: ICommandBarItemProps[] = [
    {
        key: 'start',
        id:'job_start',
        text: '启动',
        iconProps: { iconName: 'Play' },
        onClick: (ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
          if(bodyControl!=null){
            let seljobs=bodyControl._jobSelection.getSelection();
            if(seljobs && seljobs.length>0){ 
              JobExeAction(bodyControl,seljobs[0],item?.key); 
            }else{
              bodyControl.setState({jobactionButtonId:'job_start',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
            }
          }
        },
    },
    {
        key: 'pause',
        id:'job_pause',
        text: '暂停',
        iconProps: { iconName: 'Pause' },
        onClick: (ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
          if(bodyControl!=null){
            let seljobs=bodyControl._jobSelection.getSelection();
            if(seljobs && seljobs.length>0){
              JobExeAction(bodyControl,seljobs[0],item?.key);
            }else{
              bodyControl.setState({jobactionButtonId:'job_pause',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
            }
          }
        }
    },
    {
        key: 'sync',
        text: '刷新',
        iconProps: { iconName: 'SyncToPC' },
        onClick: () => {
          if(bodyControl!=null){
            LoadJobs(bodyControl);
          }
        },
    },
    {
      key: 'addJob',
      text: '新增作业',
      iconProps: { iconName: 'CalculatorAddition' },
      onClick: () =>{
        if(bodyControl!=null){
          bodyControl.setState({
            newJobDetail:{
              assemblyName:"", 
              concurrent:false,
              description:"",
              groupName:"",
              includeAnnotations:false,
              jobId:"",
              jobType:"",
              properties:"{}",
              cronList:[],
            },
            hideJobEditorDialog:false
          });
        }
      },
    },
    {
      key: 'edit',
      text: '修改作业',
      id:'job_edit',
      iconProps: { iconName: 'WindowEdit' },
      onClick: (ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
        let seljobs=bodyControl._jobSelection.getSelection();
        if(seljobs && seljobs.length>0){
          let selJob=seljobs[0];
          const cronlist=getCronList(selJob,bodyControl.state.jobListData); 
          selJob.cronList=cronlist;
          bodyControl.setState({
            newJobDetail:selJob,
            hideJobEditorDialog:false 
          });
        }else{
          bodyControl.setState({jobactionButtonId:'job_edit',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
        }
      },
    },
    {
      key: 'remove',
      text: '删除作业',
      id:'job_remove',
      iconProps: { iconName: 'Cancel' },
      onClick: (ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
        if(bodyControl!=null){ 
          let seljobs=bodyControl._jobSelection.getSelection();
          if(seljobs && seljobs.length>0){  
            //询问是否删除
            bodyControl.setState({jobactionButtonId:'job_remove',jobactionBubbleVisible:true,jobactionBubbleIsDel:true,jobactionBubbleMsg:'确定删除 作业【'+seljobs[0].jobId+'】 吗?'}); 
            //JobExeAction(bodyControl,seljobs[0],item?.key); 
          }else{
            bodyControl.setState({jobactionButtonId:'job_remove',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
          }
        }
      },
    },
  ];
  
const rl_menu_overflowItems: ICommandBarItemProps[] = [
    { key: 'excel', text: '导出excel', onClick: () => console.log('Move to'), iconProps: { iconName: 'ExcelLogoInverse' } },
    { key: 'pdf', text: '导出PDF', onClick: () => console.log('Copy to'), iconProps: { iconName: 'PDF' } },
    { key: 'png', text: '导出图片', onClick: () => console.log('Rename'), iconProps: { iconName: 'FileImage' } },
  ];
  
const rl_menu_farItems: ICommandBarItemProps[] = [
    {
      key: 'tile',
      text: 'Grid view',
      // This needs an ariaLabel since it's icon-only
      ariaLabel: 'Grid view',
      iconOnly: true,
      iconProps: { iconName: 'Tiles' },
      onClick: () => console.log('Tiles'),
    },
    {
      key: 'info',
      text: 'Info',
      // This needs an ariaLabel since it's icon-only
      ariaLabel: 'Info',
      iconOnly: true,
      iconProps: { iconName: 'Info' },
      onClick: () => console.log('Info'),
    },
  ];

const settingIcon: IIconProps = { iconName: 'PlayerSettings' };
const opButtonIcon: IIconProps = { iconName: 'MoreVertical' };
 

const TeachingBtnProps:IButtonProps = {
  children:'确定',
  onClick:()=>{
    if(bodyControl!=null){
      bodyControl.setState({jobactionBubbleVisible:false});
    }
  },
};
const TeachingBtnProps2:IButtonProps = {
  children:'确定删除',
  onClick:()=>{
    if(bodyControl!=null){
      let seljobs=bodyControl._jobSelection.getSelection();
      JobExeAction(bodyControl,seljobs[0],"remove");
      bodyControl.setState({jobactionBubbleVisible:false,jobactionBubbleIsDel:false});
    }
  },
};
const TeachingDelBtnProps:IButtonProps = {
  children: '取消',
  onClick:()=>{
    if(bodyControl!=null){
      if(bodyControl!=null){
        bodyControl.setState({jobactionBubbleVisible:false});
      }
    }
  },
};

const JobEditorModelProps = {
  isBlocking: true,
  topOffsetFixed: true,
  innerWidth:700,
};

const listIemMenuProps: IContextualMenuProps ={
  shouldFocusOnMount: true,
  styles:{
    container:{width:120,},
    list:{width:120,}
  },
  items: [
    { key:'menuitem_start', iconProps: { iconName: 'Play' }, text: '启动',onClick:()=>{
      if(bodyControl!=null){
        let seljobs=bodyControl._jobSelection.getSelection();
        if(seljobs && seljobs.length>0){ 
            JobExeAction(bodyControl,seljobs[0],"start"); 
        }else{
            bodyControl.setState({jobactionButtonId:'job_start',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
        }
      }
    } },
    {key: 'menuitem_pause',iconProps: { iconName: 'Pause'},text: '暂停',onClick:()=>{
      if(bodyControl!=null){
          let seljobs=bodyControl._jobSelection.getSelection();
          if(seljobs && seljobs.length>0){
              JobExeAction(bodyControl,seljobs[0],"pause");
          }else{
              bodyControl.setState({jobactionButtonId:'job_pause',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
          }
      }
    }}, 
    { key:'menuitem_edit', iconProps: { iconName: 'WindowEdit' }, text: '修改',onClick:()=>{
      let seljobs=bodyControl._jobSelection.getSelection();
      if(seljobs && seljobs.length>0){
          let selJob=seljobs[0];
          const cronlist=getCronList(selJob,bodyControl.state.jobListData); 
          selJob.cronList=cronlist;
          bodyControl.setState({
            newJobDetail:selJob,
            hideJobEditorDialog:false 
          });
      }else{
          bodyControl.setState({jobactionButtonId:'job_edit',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
      }
    }},
    { key:'menuitem_remove', iconProps: { iconName: 'Cancel', style: { color: 'salmon' } }, text: '删除',onClick:()=>{
      if(bodyControl!=null){ 
        let seljobs=bodyControl._jobSelection.getSelection();
        if(seljobs && seljobs.length>0){  
            //询问是否删除
            bodyControl.setState({jobactionButtonId:'job_remove',jobactionBubbleVisible:true,jobactionBubbleIsDel:true,jobactionBubbleMsg:'确定删除 作业【'+seljobs[0].jobId+'】 吗?'}); 
            //JobExeAction(bodyControl,seljobs[0],item?.key); 
        }else{
            bodyControl.setState({jobactionButtonId:'job_remove',jobactionBubbleVisible:true,jobactionBubbleIsDel:false});
        }
      }
    }}, 
  ],
}; 

let bodyControl={};

class BodyProvit extends Component <any, any>{ 
  private _jobSelection: Selection;
  private JobEditor:any;
  constructor(props){
    super(props);
   
    this.JobEditor = React.createRef();
    this._jobSelection = new Selection({
      onSelectionChanged: () =>{},
    });
   
    this.state={
      jobListData:[],
      triggerisOpen:false,
      jobListFilter:'',
      datalist:[],
      _columns:[
        { key: 'jobId', name: '任务ID', fieldName: 'jobId', minWidth: 80, maxWidth: 80, isResizable: false },
        { key: 'status', name: '状态', fieldName: 'status', minWidth: 80, maxWidth: 80, isResizable: false,onRender: (item: IDocument) => (
          trigeerStatusFormat(item.status)
        )},
        { key: 'triggerNum', name: '触发器', fieldName: 'triggerNum', minWidth: 80, maxWidth: 80, isResizable: false,onRender: (item: IDocument) => (
          <Link styles={linkStyles} onClick={this.clickOntrigger.bind(this)} data-jobid={item.jobId}>{item.triggerNum}</Link>
        )},
        { key: 'groupName', name: '分组', fieldName: 'groupName', minWidth: 80, maxWidth: 120, isResizable: false },
        { key: 'jobType', name: '任务类型', fieldName: 'jobType', minWidth: 120, maxWidth: 150, isResizable: false },
        { key: 'description', name: '备注', fieldName: 'description',isResizable: false },
        { key: 'assemblyName', name: '程序集名称', fieldName: 'assemblyName', minWidth: 100, maxWidth: 150, isResizable: false },
        { key: 'concurrent', name: '是否并行', fieldName: 'concurrent',minWidth: 80, maxWidth: 80, isResizable: false,onRender: (item: IDocument) => (
          item.concurrent?<div className='concurrenttxt cx'>并行</div>:<div className='concurrenttxt bx'>串行</div>
        )},
        { key: 'includeAnnotations', name: '注解', fieldName: 'includeAnnotations',minWidth: 80, maxWidth: 80,isResizable: false,onRender: (item: IDocument) => (
          item.includeAnnotations?<Checkbox defaultChecked disabled/>:<Checkbox disabled/>
        )},
        { key: 'properties', name: '属性', fieldName: 'properties', minWidth: 60, maxWidth: 100, isResizable: false },
        { key: 'updatedTime', name: '更新时间', fieldName: 'updatedTime',minWidth: 120, maxWidth: 150, isResizable: false },
        { key: 'extcol', name: '操作', fieldName: '',minWidth: 60, maxWidth: 60, isResizable: false,onRender: (item: IDocument) => (
          <DefaultButton styles={opButtonStyles} key='extbtn'  text='' menuProps={listIemMenuProps} menuIconProps={opButtonIcon} allowDisabledFocus/>
        )},
      ],
      triggers:[],
      jobactionBubbleVisible:false,
      jobactionBubbleIsDel:false,
      jobactionBubbleMsg:'',
      jobactionButtonId:'',
      messageBarVisable:false,
      messageBarType:MessageBarType,
      messageBarMsgContent:'',
      hideJobEditorDialog:true,
      JobEditorTitle:'',
      savejobFunc:Function,
      newJobDetail:{
        assemblyName:"", 
        concurrent:false,
        description:"",
        groupName:"",
        includeAnnotations:false,
        jobId:"",
        jobType:"",
        properties:"{}",
        cronList:[],
      },
      showCallout:false,
    }
  }


  render(){
    return (
      <>
        <Pivot styles={pivotStyles} className={pivotitemClass}  aria-label="任务列表">
          <PivotItem headerText="任务列表" itemIcon="Ringer"> 
            <Stack styles={rl_stack_v_styles} tokens={innerStackTokens}>
                <Stack.Item>
                    <Stack styles={rl_stack_styles} horizontal tokens={innerStackTokens}>
                        <Stack.Item styles={rl_stackitem_styles} grow >
                            <Pivot styles={pivot2Styles} className='team_header' aria-label="团队资源" onLinkClick={this.jobListFilterClick}>
                                <PivotItem headerText="全部">
                                </PivotItem>
                                <PivotItem headerText="正常">
                                </PivotItem>
                                <PivotItem headerText="已暂停">
                                </PivotItem>
                            </Pivot>
                        </Stack.Item>
                        <Stack.Item styles={rl_stackitem_msgbar_styles} grow>
                          {
                            this.state.messageBarVisable &&(
                              <MessageBar
                              delayedRender={false}
                              messageBarType={this.state.messageBarType}
                              // role="alert"
                            >
                              {this.state.messageBarMsgContent}
                            </MessageBar>
                            )
                          }
                        </Stack.Item>
                        <Stack.Item  grow styles={rl_stackitem_vedio_styles} >
                            <DefaultButton styles={settingButtonStyles} toggle  text='设置' iconProps={settingIcon} allowDisabledFocus/>
                        </Stack.Item>
                    </Stack>
                </Stack.Item>
                <Stack.Item>
                  <CommandBar className={'rtlCommandBar'} styles={commandButtonStyls}
                        items={rl_menu_items}
                        overflowItems={rl_menu_overflowItems}
                        overflowButtonProps={overflowProps}
                        farItems={rl_menu_farItems}
                        ariaLabel="Inbox actions"
                        primaryGroupAriaLabel="Email actions"
                        farItemsGroupAriaLabel="More actions"
                    />
                </Stack.Item>
                <Stack.Item styles={datalist_stack_styles}>
                  <div className={DataListClass.wrapper}>
                    <ScrollablePane scrollContainerFocus={true}>
                      <DetailsList
                              items={this.state.datalist}
                              columns={this.state._columns}
                              setKey="jobId" 
                              selection={this._jobSelection}
                              selectionMode={SelectionMode.single}
                              layoutMode={DetailsListLayoutMode.justified} 
                              selectionPreservedOnEmptyClick={true}
                              ariaLabelForSelectionColumn="Toggle selection"
                              ariaLabelForSelectAllCheckbox="Toggle selection for all items"
                              checkButtonAriaLabel="select row" 
                            /> 
                    </ScrollablePane>
                  </div>
                </Stack.Item>
            </Stack>
              <Panel 
                type={PanelType.custom}
                customWidth="400px"
                headerText="触发器详情"
                isOpen={this.state.triggerisOpen}
                onDismiss={()=>this.setState({triggerisOpen:false})}
                closeButtonAriaLabel="Close"
              >
                <JobTrigger triggers={this.state.triggers}></JobTrigger>
              </Panel>
              {this.state.jobactionBubbleVisible && !this.state.jobactionBubbleIsDel && (
                <TeachingBubble
                  target={`#`+this.state.jobactionButtonId}
                  primaryButtonProps={TeachingBtnProps} 
                  hasSmallHeadline={true}
                  onDismiss={()=>this.setState({jobactionBubbleVisible:false})}
                  headline={this.state.jobactionBubbleIsDel?"删除确认":"无法执行操作"}
                  closeButtonAriaLabel="Close"
                >
                  {this.state.jobactionBubbleIsDel?this.state.jobactionBubbleMsg:"无法响应您的动作,请您先选择 Job(任务) 后再试！"}
                </TeachingBubble>
              )}
              {this.state.jobactionBubbleVisible && this.state.jobactionBubbleIsDel && (
                <TeachingBubble
                  target={`#`+this.state.jobactionButtonId}
                  primaryButtonProps={TeachingBtnProps2}
                  secondaryButtonProps={TeachingDelBtnProps}
                  hasSmallHeadline={true}
                  onDismiss={()=>this.setState({jobactionBubbleVisible:false})}
                  headline={this.state.jobactionBubbleIsDel?"删除确认":"无法执行操作"}
                  closeButtonAriaLabel="Close"
                >
                  {this.state.jobactionBubbleIsDel?this.state.jobactionBubbleMsg:"无法响应您的动作,请您先选择 Job(任务) 后再试！"}
                </TeachingBubble>
              )}
              <Dialog title={this.state.JobEditorTitle} hidden={this.state.hideJobEditorDialog} onDismiss={()=>this.setState({hideJobEditorDialog:true})} modalProps={JobEditorModelProps} maxWidth={700}>
                <JobEditor newJobDetail={this.state.newJobDetail} ref={this.JobEditor}></JobEditor>
                <DialogFooter>
                  <PrimaryButton onClick={this._saveJobDetail.bind(this)} text="确定" />
                  <DefaultButton onClick={()=>this.setState({hideJobEditorDialog:true})} text="取消" />
                </DialogFooter>
              </Dialog>
          </PivotItem>
          {/* <PivotItem headerText="聊天" itemCount={23} itemIcon="Comment"> */}
          <PivotItem headerText="聊天"itemIcon="Comment">
          <Label styles={labelStyles}>Pivot #2</Label>
          </PivotItem>
          <PivotItem headerText="团队" itemIcon="Teamwork">
              <ProvitTeam></ProvitTeam>
          </PivotItem>
        </Pivot>
      </>
    );
  }
  componentDidMount(){
    const Me=this;
    console.log("=================组件已经挂载了"); 
    LoadJobs(Me);
    bodyControl=Me;
  }

  clickOntrigger(this,ev: React.MouseEvent<unknown>){
    const Me=this;
    const jobId=ev.currentTarget.attributes["data-jobid"].value; 
    let _temptriggers=[];
    for (let item of Me.state.jobListData) {
      if(item.jobDetail.jobId===jobId){
        _temptriggers=item.triggers;
        break;    
      }
    }
    Me.setState({triggerisOpen:true,triggers:_temptriggers});
  }

  jobListFilterClick(item?: PivotItem, ev?: React.MouseEvent<HTMLElement>){
    let  _filterType =String.apply("");
    let _filterdata=Array<Object>();
    if(bodyControl){
      if(item.props.headerText==="全部"){
        _filterType="";
        _filterdata=JobFilter(bodyControl.state.jobListData,_filterType);
      }
      if(item.props.headerText==="正常"){
        _filterType="nomal";
        _filterdata=JobFilter(bodyControl.state.jobListData,_filterType);
      }
      if(item.props.headerText==="已暂停"){
        _filterType="pause";
        _filterdata=JobFilter(bodyControl.state.jobListData,_filterType);
      }
      bodyControl.setState({
        jobListFilter:_filterType,
        datalist:_filterdata,
      })
    }
  }
  _saveJobDetail(){
    let Me=this; 
    Me.JobEditor.current.saveJobDetail(function(){
      LoadJobs(Me);
    }); 
  }
};

function LoadJobs(_control){ 
  http.get("schedule/api/get-jobs",{}).then(function(result){  
    if(result.data.code===200){
      _control.setState({
        hideJobEditorDialog:true,
        jobListData:result.data.data,
        datalist:JobFilter(result.data.data,_control.state.jobListFilter),//过滤数据
        selectedItem:{},
      });
    }else{
      console.log("获取作业列表失败："+result.data.msg); 
      _control.setState({
        hideJobEditorDialog:true,
        jobListData:[],
        datalist:JobFilter([],_control.state.jobListFilter),//过滤数据
        selectedItem:{},
      });
    }
  });
}
function JobFilter(_alldata,_filtertype){
  let tempdata=Array<Object>();
  _alldata.forEach(element => {
    element.jobDetail.triggerNum=element.triggers.length;
    element.jobDetail.status=(element.triggers.length>0)?element.triggers[0].status:11;
    if(_filtertype!=null && _filtertype===""){
      tempdata.push(element.jobDetail);
    }
    if(_filtertype!=null && _filtertype==='nomal' && ([1,2,5].indexOf(element.jobDetail.status)>-1)){
      tempdata.push(element.jobDetail);
    }
    if(_filtertype!=null && _filtertype==='pause' && element.jobDetail.status===3){
      tempdata.push(element.jobDetail);
    }
  }); 
  return tempdata
}

function JobExeAction(_control,_job,_action){
  let opPars="jobid="+_job.jobId+"&action="+_action;
  http.get("schedule/api/operate-job?"+opPars,{}).then(function(result){ 
    if(result.data.code===200){
      showMessageBar(_control,MessageBarType.success,_action,(_action==='start')?'作业【'+_job.jobId+'】成功!':'作业【'+_job.jobId+'】成功!');
      LoadJobs(_control);
      HideMessageBar(_control);
    }else{ 
      console.log("作业操作失败失败："+result.data.msg); 
      showMessageBar(_control,MessageBarType.error,_action,(_action==='start')?'作业【'+_job.jobId+'】失败!':'作业【'+_job.jobId+'】失败!');
      HideMessageBar(_control);
    }
  });
}

function showMessageBar(control:BodyProvit,type:MessageBarType,actiontype:String,msgcontent:String){
  if(actiontype==="start") msgcontent="启动 "+msgcontent;
  if(actiontype==="pause") msgcontent="暂停 "+msgcontent;
  if(actiontype==="remove") msgcontent="删除 "+msgcontent;
  control.setState({
    messageBarVisable:true,
    messageBarType:type,
    messageBarMsgContent:msgcontent,
  })
}
function HideMessageBar(control:BodyProvit){
  setTimeout(() => {
    control.setState({messageBarVisable:false})
  }, 1000);
}

function trigeerStatusFormat(_statusCode){
  if(_statusCode===0) return <div className='status_tag alrm'>积压</div>
  if(_statusCode===1) return <div  className='status_tag succed'>正常/就绪</div>
  if(_statusCode===2) return <div  className='status_tag succed'>运行</div>
  if(_statusCode===3) return <div  className='status_tag nomal'>暂停</div>
  if(_statusCode===4) return <div className='status_tag alrm'>阻塞</div>
  if(_statusCode===5) return <div  className='status_tag succed'>正常/就绪*</div>
  if(_statusCode===6) return <div  className='status_tag nomal'>归档</div>
  if(_statusCode===7) return <div className='status_tag alrm'>崩溃</div>
  if(_statusCode===8) return <div className='status_tag alrm'>超限</div>
  if(_statusCode===9) return <div  className='status_tag nomal'>无触发时间</div>
  if(_statusCode===10) return <div className='status_tag alrm'>初始未启动</div>
  if(_statusCode===11) return <div className='status_tag alrm'>未知触发器</div>
  if(_statusCode===12) return <div className='status_tag alrm'>未知处理程序</div>
}
function getCronList(_seljob,_joblist){
  let selTriggerList:Array<Object>=[];
  let cronlist:Array<Object>=[];
  if(_joblist && _joblist.length>0){ 
    for(let item of _joblist){
      if(item.jobDetail.jobId===_seljob.jobId){
        selTriggerList=item.triggers;
        break;
      }
    }
  }
  if(selTriggerList && selTriggerList.length>0){
    selTriggerList.forEach(element => {
      cronlist.push({id:element.triggerId,cron:JSON.parse(element.args)[0],visbale:true})
    });
  }
  return cronlist;
}
export default BodyProvit